import sys
from PyQt6.QtWidgets import QApplication, QMessageBox
from PyQt6.QtGui import QIcon
from ui.main_window import MainWindow
import warnings
from utils.logger import Logger
import traceback
import os

# 设置编码
os.environ['PYTHONIOENCODING'] = 'utf-8'
if sys.platform == 'win32':
    import locale
    try:
        locale.setlocale(locale.LC_ALL, 'zh_CN.UTF-8')
    except locale.Error:
        try:
            locale.setlocale(locale.LC_ALL, 'Chinese_China.UTF8')
        except locale.Error:
            try:
                locale.setlocale(locale.LC_ALL, '')  # 使用系统默认
            except locale.Error:
                pass  # 忽略设置失败

# 确保日志目录存在
os.makedirs('logs', exist_ok=True)

# 获取日志实例
logger = Logger.get_logger()

def show_error_dialog(title, message):
    """显示错误对话框"""
    try:
        app = QApplication.instance()
        if not app:
            app = QApplication(sys.argv)
        QMessageBox.critical(None, title, message)
    except Exception as e:
        logger.error(f"显示错误对话框失败: {str(e)}")

def exception_handler(exc_type, exc_value, exc_traceback):
    """全局异常处理"""
    error_msg = (
        "未捕获的异常:\n"
        f"类型: {exc_type.__name__}\n"
        f"信息: {str(exc_value)}\n"
        f"堆栈跟踪:\n{traceback.format_exc()}"
    )
    logger.error(error_msg)
    show_error_dialog("错误", f"程序遇到错误:\n{str(exc_value)}")

def main():
    try:
        # 记录启动环境信息
        logger.info("=== 启动喵神AI应用程序 ===")
        logger.info(f"Python版本: {sys.version}")
        logger.info(f"工作目录: {os.getcwd()}")
        logger.info(f"命令行参数: {sys.argv}")
        
        # 设置全局异常处理
        sys.excepthook = exception_handler
        
        # 创建应用
        app = QApplication(sys.argv)
        logger.debug("QApplication初始化完成")
        
        # 设置应用信息
        app.setApplicationName("喵神AI")
        app.setApplicationVersion("1.0.0")
        app.setOrganizationName("MiaoShenAI")
        logger.debug("应用信息设置完成")
        
        # 检查资源文件
        resources_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'resources')
        if not os.path.exists(resources_path):
            raise FileNotFoundError(f"找不到资源目录: {resources_path}")
        logger.debug(f"资源目录检查完成: {resources_path}")
        
        # 创建主窗口
        window = MainWindow()
        logger.debug("主窗口创建完成")
        
        # 显示窗口
        window.show()
        logger.info("应用程序界面显示完成")
        
        # 运行应用
        exit_code = app.exec()
        logger.info(f"应用程序退出，退出码: {exit_code}")
        return exit_code
        
    except Exception as e:
        error_msg = (
            f"应用程序启动失败:\n"
            f"错误信息: {str(e)}\n"
            f"堆栈跟踪:\n{traceback.format_exc()}"
        )
        logger.error(error_msg)
        show_error_dialog("启动失败", f"程序启动失败:\n{str(e)}")
        return 1

if __name__ == '__main__':
    try:
        sys.exit(main())
    except Exception as e:
        logger.error(f"主程序异常退出: {str(e)}")
        sys.exit(1) 